import tkinter as tk
from tkinter import ttk, filedialog, messagebox
import requests
import hashlib
import uuid
from srt import parse, compose
import threading
import json
import os
import time


# 配置文件路径（跨平台兼容）
CONFIG_PATH = os.path.join(os.path.expanduser("~"), ".subtitle_translator_config.json")

class TranslatorApp:
    def __init__(self, root):
        self.root = root
        root.title("字幕翻译工具 - 百度API版")
        root.geometry("500x400")  # 设置窗口大小
        
        # 加载历史配置
        self.config = self.load_config()
        
        # 创建界面组件
        self.create_widgets()

    def create_widgets(self):
        # 配置文件选择
        file_frame = ttk.Frame(self.root)
        file_frame.pack(pady=10, padx=10, fill="x")
        
        ttk.Label(file_frame, text="字幕文件:").pack(side="left")
        self.file_path = tk.StringVar()
        ttk.Entry(file_frame, textvariable=self.file_path, width=40).pack(side="left", padx=5)
        ttk.Button(file_frame, text="浏览", command=self.browse_file).pack(side="left")

        # API配置输入
        config_frame = ttk.LabelFrame(self.root, text="API配置")
        config_frame.pack(pady=10, padx=10, fill="x")
        
        ttk.Label(config_frame, text="APP ID:").grid(row=0, column=0, padx=5, sticky="w")
        self.app_id_entry = ttk.Entry(config_frame, width=40)
        self.app_id_entry.grid(row=0, column=1, padx=5)
        if self.config.get("app_id"):
            self.app_id_entry.insert(0, self.config["app_id"])

        ttk.Label(config_frame, text="Secret Key:").grid(row=1, column=0, padx=5, sticky="w")
        self.secret_key_entry = ttk.Entry(config_frame, width=40, show="*")
        self.secret_key_entry.grid(row=1, column=1, padx=5)
        if self.config.get("secret_key"):
            self.secret_key_entry.insert(0, self.config["secret_key"])

        # 翻译设置
        setting_frame = ttk.LabelFrame(self.root, text="翻译设置")
        setting_frame.pack(pady=10, padx=10, fill="x")
        
        ttk.Label(setting_frame, text="目标语言:").grid(row=0, column=0, padx=5, sticky="w")
        self.lang_var = tk.StringVar(value=self.config.get("target_lang", "zh"))
        ttk.Combobox(setting_frame, textvariable=self.lang_var, values=["zh", "en", "jp"], width=10).grid(row=0, column=1, sticky="w")

        # 进度条和百分比显示
        progress_frame = ttk.Frame(self.root)
        progress_frame.pack(pady=10, padx=10, fill="x")
        
        self.progress = ttk.Progressbar(progress_frame, orient="horizontal", mode="determinate")
        self.progress.pack(side="left", expand=True, fill="x")
        
        self.percent_label = ttk.Label(progress_frame, text="0%", width=5)
        self.percent_label.pack(side="left", padx=5)

        # 操作按钮
        btn_frame = ttk.Frame(self.root)
        btn_frame.pack(pady=10)
        ttk.Button(btn_frame, text="开始翻译", command=self.start_translation).pack(side="left", padx=5)

        # 窗口关闭事件
        self.root.protocol("WM_DELETE_WINDOW", self.on_close)

    def browse_file(self):
        """浏览字幕文件"""
        filetypes = [("字幕文件", "*.srt *.vtt *.ass"), ("所有文件", "*.*")]
        filename = filedialog.askopenfilename(filetypes=filetypes)
        if filename:
            self.file_path.set(filename)

    def load_config(self):
        """加载配置文件"""
        try:
            if os.path.exists(CONFIG_PATH):
                with open(CONFIG_PATH, "r") as f:
                    return json.load(f)
        except Exception as e:
            messagebox.showwarning("配置错误", f"加载配置失败: {str(e)}")
        return {}

    def save_config(self):
        """保存配置"""
        try:
            config = {
                "app_id": self.app_id_entry.get().strip(),
                "secret_key": self.secret_key_entry.get().strip(),
                "target_lang": self.lang_var.get()
            }
            with open(CONFIG_PATH, "w") as f:
                json.dump(config, f)
        except Exception as e:
            messagebox.showerror("保存失败", f"无法保存配置: {str(e)}")

    def on_close(self):
        """窗口关闭事件"""
        self.save_config()
        self.root.destroy()

    def baidu_translate(self, text, from_lang='en', to_lang='zh'):
        """调用翻译API"""
        try:
            salt = str(uuid.uuid1())
            sign_str = self.app_id_entry.get().strip() + text + salt + self.secret_key_entry.get().strip()
            sign = hashlib.md5(sign_str.encode()).hexdigest()
            
            params = {
                'q': text,
                'from': from_lang,
                'to': to_lang,
                'appid': self.app_id_entry.get().strip(),
                'salt': salt,
                'sign': sign
            }
            
            response = requests.get("https://fanyi-api.baidu.com/api/trans/vip/translate", params=params)
            result = response.json()
            return result['trans_result'][0]['dst']
        except Exception as e:
            messagebox.showerror("翻译错误", f"API请求失败: {str(e)}")
            return None

    def translation_thread(self):
        """执行翻译的线程"""
        if not all([self.app_id_entry.get().strip(), self.secret_key_entry.get().strip(), self.file_path.get()]):
            messagebox.showwarning("输入错误", "请填写所有必填字段")
            return

        try:
            start_time = time.time()  # 记录开始时间
            with open(self.file_path.get(), "r", encoding="utf-8") as f:
                subs = list(parse(f.read()))
            
            total = len(subs)
            self.progress["maximum"] = total
            
            translated_subs = []
            for i, sub in enumerate(subs):
                translated_text = self.baidu_translate(sub.content, to_lang=self.lang_var.get())
                if not translated_text:
                    return
                sub.content = translated_text
                translated_subs.append(sub)
                
                # 更新进度和百分比
                self.progress["value"] = i+1
                percent = (i+1) / total * 100
                self.percent_label.config(text=f"{percent:.1f}%")
                self.root.update_idletasks()
            
            output_path = self.file_path.get().replace(".srt", f"_translated_{self.lang_var.get()}.srt")
            end_time = time.time()
            duration = self.format_duration(end_time - start_time)
            with open(output_path, "w", encoding="utf-8") as f:
                f.write(compose(translated_subs))
            
            messagebox.showinfo("完成", f"翻译成功！耗时 {duration}\n文件已保存至:\n{output_path}")  # 新增耗时显示
        except Exception as e:
            messagebox.showerror("错误", f"处理文件时发生错误: {str(e)}")
        finally:
            self.progress["value"] = 0
            self.percent_label.config(text="0%")

    def start_translation(self):
        """启动翻译线程"""
        threading.Thread(target=self.translation_thread, daemon=True).start()

    def format_duration(self, seconds):
        """将秒数格式化为易读的时间"""
        minutes, seconds = divmod(seconds, 60)
        if minutes > 0:
            return f"{int(minutes)}分{seconds:.1f}秒"
        else:
            return f"{seconds:.1f}秒"
        

if __name__ == "__main__":
    root = tk.Tk()
    app = TranslatorApp(root)
    root.mainloop()
